<template>
  <div>
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row style="margin-bottom: 15px;">
        <el-col>
          <el-button type="primary" @click="showAddCateDialog"
            >添加分类</el-button
          >
        </el-col>
      </el-row>

      <tree-table
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
        :show-row-hover="false"
      >
        <template slot="isOK" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: lightgreen;font-size: 20px"
          ></i>
          <i
            class="el-icon-error"
            v-else
            style="color: red;font-size: 20px"
          ></i>
        </template>

        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag v-else-if="scope.row.cat_level === 1" type="success"
            >二级</el-tag
          >
          <el-tag v-else type="warning">三级</el-tag>
        </template>

        <template slot="opt" slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditCate(scope.row)"
            >编辑</el-button
          >
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeCate(scope.row)"
            >删除</el-button
          >
        </template>
      </tree-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加分类 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateVisible"
      width="30%"
      @close="addCateDialogClosed"
    >
      <el-form
        :model="addCateForm"
        :rules="addCateRules"
        ref="addCateRulesRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            clearable
            ref="parentCateRef"
            v-model="selectedKeys"
            :options="parentCateList"
            :props="parentCateListProps"
            @change="parentCateChange"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addCateVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑分类名称 -->
    <el-dialog
      title="编辑分类"
      :visible.sync="editCateVisible"
      width="30%"
      @close="editCateDialogClosed"
    >
      <el-form
        :model="editCateForm"
        :rules="editCateRules"
        ref="editCateRulesRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editCateVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryInfo: {
        type: [1, 2, 3],
        pagenum: 1,
        pagesize: 5
      },
      cateList: [],
      total: 0,
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          // 将当前列定义为模板列
          type: 'template',
          // 当前这一列使用模板名称 用插槽
          template: 'isOK'
        },
        {
          label: '排序',
          type: 'template',
          // 当前这一列使用模板名称 用插槽
          template: 'order'
        },
        {
          label: '操作',
          type: 'template',
          // 当前这一列使用模板名称 用插槽
          template: 'opt'
        }
      ],
      // 添加分类
      addCateVisible: false,
      addCateForm: {
        cat_name: '',
        cat_pid: 0, // 分类父ID
        cat_level: 0 // 分类层级
      },
      addCateRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      selectedKeys: [],
      parentCateList: [],
      parentCateListProps: {
        expandTrigger: 'hover',
        checkStrictly: 'true',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 编辑分类
      editCateVisible: false,
      editCateForm: {
        cat_name: '',
        cat_id: 0
      },
      editCateRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      }
    }
  },
  activated() {},
  watch: {
    selectedKeys() {
      this.$refs.parentCateRef.dropDownVisible = false
    }
  },
  created() {
    this.getCateList()
  },
  mounted() {},
  methods: {
    handleCurrentChange(e) {
      this.queryInfo.pagenum = e
      this.getCateList()
    },
    handleSizeChange(e) {
      this.queryInfo.pagesize = e
      this.getCateList()
    },
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data.result
      this.total = res.data.total
      // console.log(res)
    },
    // 添加分类
    showAddCateDialog() {
      this.addCateVisible = true
      this.getParentList()
    },
    addCateDialogClosed() {
      this.$refs.addCateRulesRef.resetFields()
      this.selectedKeys = []
      this.addCateForm.cat_level = 0
      this.addCateForm.cat_pid = 0
    },
    async getParentList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      if (res.meta.status !== 200) return this.$message.error('父级分类列表获取失败')
      this.parentCateList = res.data
    },
    addCate() {
      this.$refs.addCateRulesRef.validate(async valid => {
        if (!valid) return this.$message.error('请输入分类名称')
        const { data: res } = await this.$http.post(
          'categories',
          this.addCateForm
        )
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加分类失败')
        this.$message.success('添加分类成功')
        this.getCateList()
        this.addCateVisible = false
      })
    },
    parentCateChange(e) {
      this.addCateForm.cat_pid = e[e.length - 1]
      this.addCateForm.cat_level = e.length
    },

    // 删除分类
    removeCate(row) {
      this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`categories/${row.cat_id}`)
          // console.log(res)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          this.getCateList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      console.log(row)
    },
    // 编辑分类
    showEditCate(row) {
      console.log(row)
      this.editCateVisible = true
      this.editCateForm.cat_name = row.cat_name
      this.editCateForm.cat_id = row.cat_id
    },
    editCate() {
      this.$refs.editCateRulesRef.validate(async valid => {
        if (!valid) return this.$message.error('请输入分类名称')
        const { data: res } = await this.$http.put(`categories/${this.editCateForm.cat_id}`, { cat_name: this.editCateForm.cat_name })
        if (res.meta.status !== 200) return this.$message.error('编辑分类失败')
        this.$message.success('编辑分类成功')
        this.getCateList()
        this.editCateVisible = false
        console.log(res)
      })
    },
    editCateDialogClosed() {
      this.$refs.editCateRulesRef.resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.el-cascader {
  width: 100%;
}
</style>
